var api = require("../../api.js"), app = getApp();

Page({
  data: {
    givegoods_list: [],
    mch_id:"",
  },
  onLoad: function (t) {
    this.setData({
      mch_id: t.mchid,
    }),this.getCartList(t);
  },
  getCartList: function (t) {
    var a = this;
    wx.showLoading({
      title: "正在加载",
      mask: !0
    }), app.request({
      url: api.order.give_goods + "&mch_id=" + t.mchid,
      success: function (t) {
        1 == t.code && a.setData({
          givegoods_list: t.data
        });
        if (a.data.givegoods_list && a.data.givegoods_list.length) for (var u in a.data.givegoods_list) {
          a.data.givegoods_list[u].num = 1;
          a.data.givegoods_list[u].max_num = JSON.parse(a.data.givegoods_list[u].attr)[0].num;
          a.setData({
            givegoods_list: a.data.givegoods_list
          })
        }
      },
      complete: function () {
        wx.hideLoading();
      }
    })

  },
  cartLess: function (t) {
    var a = this;
    var c = t.currentTarget.dataset.index;
    a.data.givegoods_list[c].num = a.data.givegoods_list[c].num - 1;
    a.setData({
      givegoods_list: a.data.givegoods_list
    });

  },
  cartAdd: function (t) {
    var a = this;
    var c = t.currentTarget.dataset.index;
    a.data.givegoods_list[c].num = a.data.givegoods_list[c].num + 1;
    a.setData({
      givegoods_list: a.data.givegoods_list
    });

  },
  cartCheck: function (t) {
    var a = this, i = t.currentTarget.dataset.index;
    a.data.givegoods_list[i].checked = !a.data.givegoods_list[i].checked;
    a.setData({
      givegoods_list: a.data.givegoods_list
    });
  },
  confirmGoods: function () {
    var a = this, goodsinfo = [];
    if (a.data.givegoods_list && a.data.givegoods_list.length) 
    for (const goodsItem of a.data.givegoods_list) {
      if (goodsItem.checked === true) {
        goodsinfo.push({ id: goodsItem.id, num: goodsItem.num });
      }
    }
    console.log(goodsinfo)
    if (goodsinfo.length == 0) {
      wx.showModal({
        title: '温馨提示',
        content: '您还没选择赠送的商品',
        cancelText: "取消",
        confirmText: "放弃",
        success: function (res) {
          console.log(res)
          if (res.confirm) {
            wx.navigateBack({
              delta: 1
            });
          }
        },
        fail: function (res) {
          console.log(res);
        }
      });
    } else {
      app.request({
        url: api.order.add_goods,
        method: "POST",
        data: {
          goods_id: JSON.stringify(goodsinfo),
          mch_id: a.data.mch_id,
        },
      
        success: function (t) {
          console.log(t);

          console.log("111 ===== " + JSON.stringify(goodsinfo));
          console.log("222 ===== " + a.data.mch_id);


          wx.navigateBack({
            delta: 1
          });

          // a.loadOrderList(a.data.status)

        }
      })
    }
    console.log(a.data.status);
    console.log(JSON.stringify(goodsinfo));

  }

});